<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="520px" :title="`${drawerProps.title}公司`">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-card header="公司基本信息" shadow="never">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="drawerProps.row!.name" placeholder="请填写公司名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="drawerProps.row!.contactName" placeholder="请填写联系人姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="drawerProps.row!.contactPhone" placeholder="请填写联系电话" clearable></el-input>
        </el-form-item>
        <el-form-item label="省份" prop="provinceId">
          <el-select v-model="drawerProps.row!.provinceId" placeholder="请选择省份" @change="getCityList">
            <el-option v-for="item in provinceList" :key="item.id" :label="item.cname" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="cityId">
          <el-select v-model="drawerProps.row!.cityId" placeholder="请选择城市" @change="getAreaList">
            <el-option v-for="item in cityList" :key="item.id" :label="item.cname" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地区" prop="areaId">
          <el-select v-model="drawerProps.row!.areaId" placeholder="请选择地区" @change="getDistrictList">
            <el-option v-for="item in districtList" :key="item.id" :label="item.cname" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="drawerProps.row!.address" placeholder="请填写详细地址" type="textarea" clearable></el-input>
        </el-form-item>
      </el-card>

      <el-card header="系统版本设置" style="margin-top: 15px">
        <el-form-item label="版本" prop="version">
          <el-select v-model="drawerProps.row!.version" placeholder="请选择系统版本">
            <el-option label="基础班" value="基础班"></el-option>
            <el-option label="专业版" value="专业版"></el-option>
            <el-option label="企业版" value="企业版"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="versionExpiryTime">
          <el-date-picker
            style="width: 100%"
            v-model="drawerProps.row!.versionExpiryTime"
            placeholder="选择过期时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="CompanyDrawer">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance, ElMessageBox } from "element-plus";
import type { Company } from "@/api/interface";
import { getSysPlacesList } from "@/api/modules/sys-places";
import { SysPlaces } from "@/api/interface";

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: "请填写公司名称", trigger: "blur" }],
  version: [{ required: true, message: "请填写版本号", trigger: "blur" }],
  versionExpiryTime: [{ required: true, message: "请选择过期时间", trigger: "change" }],
  contactName: [{ required: true, message: "请填写联系人姓名", trigger: "blur" }],
  provinceId: [{ required: true, message: "请选择省份", trigger: "change" }],
  cityId: [{ required: true, message: "请选择城市", trigger: "change" }],
  areaId: [{ required: true, message: "请选择地区", trigger: "change" }],
  contactPhone: [
    { required: true, message: "请填写联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码格式", trigger: "blur" }
  ]
});

// 挂载时加载省份数据
onMounted(async () => {
  provinceList.value = await loadSysPlaces(1);
});

// 抽屉属性接口
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Company.ResCompanyList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

// 抽屉状态
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传递的参数
defineExpose({
  acceptParams: async (params: DrawerProps) => {
    drawerProps.value = params;
    drawerVisible.value = true;

    if (drawerProps.value.row.provinceId) {
      cityList.value = await loadSysPlaces(drawerProps.value.row.provinceId);
    }
    if (drawerProps.value.row.cityId) {
      districtList.value = await loadSysPlaces(drawerProps.value.row.cityId);
    }
  }
});

// 提交表单
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;

    try {
      // 确保只有定义的字段被提交
      const submitData: Company.ReqCompanySaveParams = {
        id: drawerProps.value.row.id,
        name: drawerProps.value.row.name,
        version: drawerProps.value.row.version,
        versionExpiryTime: drawerProps.value.row.versionExpiryTime,
        provinceId: drawerProps.value.row.provinceId,
        cityId: drawerProps.value.row.cityId,
        areaId: drawerProps.value.row.areaId,
        address: drawerProps.value.row.address,
        contactName: drawerProps.value.row.contactName,
        contactPhone: drawerProps.value.row.contactPhone,
        provinceName: drawerProps.value.row.provinceName,
        cityName: drawerProps.value.row.cityName,
        areaName: drawerProps.value.row.areaName
      };

      // 调用API保存数据
      const res = await drawerProps.value.api!(submitData);

      ElMessage.success({
        message: `${drawerProps.value.title}公司成功！`
      });

      // 调用父组件的刷新表格方法
      if (drawerProps.value.getTableList) {
        drawerProps.value.getTableList();
      }

      // 关闭抽屉
      drawerVisible.value = false;

      // 新增公司时，提示初始员工账户及密码
      if (drawerProps.value.title === "新增" && res.data !== "") {
        ElMessageBox.alert(
          `管理员手机号：${submitData.contactPhone}，管理员初始密码：${res.data}，已短信告知。`,
          "新增公司成功",
          {
            confirmButtonText: "好的",
            cancelButtonText: "关闭",
            type: "success",
            center: true
          }
        );
      }
    } catch (error) {
      console.error("提交失败:", error);
      ElMessage.error("操作失败，请重试");
    }
  });
};

// 省市区处理
const provinceList = ref<SysPlaces.ResSysPlacesListDto[]>([]);
const cityList = ref<SysPlaces.ResSysPlacesListDto[]>([]);
const districtList = ref<SysPlaces.ResSysPlacesListDto[]>([]);
const loadSysPlaces = async (parentId: number) => {
  const params: SysPlaces.ReqResSysPlacesListParam = {
    getAllLevels: true,
    parentId: parentId
  };
  const res = await getSysPlacesList(params);
  return res.data || [];
};
const getCityList = async (provinceId: number) => {
  // 清空城市列表
  cityList.value = [];
  // 清空地区列表
  districtList.value = [];
  // 加载城市数据
  cityList.value = await loadSysPlaces(provinceId);

  // 设置省份名称
  drawerProps.value.row!.provinceName = provinceList.value.find(p => p.id === provinceId)?.cname || "";
  // 设置省份ID
  drawerProps.value.row!.provinceId = provinceId;

  // 清空城市名称
  drawerProps.value.row!.cityName = undefined;
  // 清空城市ID
  drawerProps.value.row!.cityId = undefined;
  // 清空地区名称
  drawerProps.value.row!.areaName = undefined;
  // 清空地区ID
  drawerProps.value.row!.areaId = undefined;
};
const getAreaList = async (cityId: number) => {
  // 清空地区列表
  districtList.value = [];
  // 加载地区数据
  districtList.value = await loadSysPlaces(cityId);

  // 设置城市名称
  drawerProps.value.row!.cityName = cityList.value.find(c => c.id === cityId)?.cname || "";
  // 设置城市ID
  drawerProps.value.row!.cityId = cityId;

  // 清空地区名称
  drawerProps.value.row!.areaName = undefined;
  // 清空地区ID
  drawerProps.value.row!.areaId = undefined;
};
const getDistrictList = async (areaId: number) => {
  // 设置地区名称
  drawerProps.value.row!.areaName = districtList.value.find(a => a.id === areaId)?.cname || "";
  // 设置地区ID
  drawerProps.value.row!.areaId = areaId;
};
</script>

<style scoped>
.employee-tabs {
  margin-top: 15px;
}
</style>
